package cn.chiship.framework.upms.biz.user.service.impl;

import cn.chiship.framework.common.constants.SystemConfigConstants;
import cn.chiship.framework.common.enums.LoginTypeEnum;
import cn.chiship.framework.common.pojo.vo.ConfigJson;
import cn.chiship.framework.common.service.GlobalCacheService;
import cn.chiship.framework.upms.biz.user.entity.*;
import cn.chiship.framework.upms.biz.user.mapper.*;
import cn.chiship.framework.upms.biz.user.pojo.vo.UpmsUserVo;
import cn.chiship.framework.upms.biz.user.service.UpmsUserLoginHistoryService;
import cn.chiship.framework.upms.biz.user.service.UpmsUserOnlineService;
import cn.chiship.framework.upms.biz.user.service.UpmsUserService;
import cn.chiship.sdk.cache.util.JwtUtil;
import cn.chiship.sdk.cache.vo.CacheDepartmentVo;

import cn.chiship.sdk.cache.service.UserCacheService;
import cn.chiship.sdk.cache.vo.CacheOrganizationVo;
import cn.chiship.sdk.cache.vo.CacheRoleVo;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.base.constants.RegularExpressionConstants;
import cn.chiship.sdk.core.encryption.Md5Util;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.enums.UserTypeEnum;
import cn.chiship.sdk.core.exception.ExceptionUtil;
import cn.chiship.sdk.core.exception.custom.BusinessException;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.*;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.sdk.framework.pojo.vo.PageVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 用户业务接口实现层
 * 2021/9/27
 *
 * @author lijian
 */
@Service
public class UpmsUserServiceImpl extends BaseServiceImpl<UpmsUser, UpmsUserExample> implements UpmsUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsUserServiceImpl.class);

    @Resource
    UpmsUserMapper upmsUserMapper;
    @Resource
    UpmsRoleMapper upmsRoleMapper;
    @Resource
    UpmsOrganizationMapper upmsOrganizationMapper;
    @Resource
    UserCacheService userCacheService;
    @Resource
    UpmsUserOrganizationMapper upmsUserOrganizationMapper;
    @Resource
    UpmsUserRoleMapper upmsUserRoleMapper;
    @Resource
    UpmsUserLoginHistoryService upmsUserLoginHistoryService;
    @Resource
    private UpmsPermissionApiMapper upmsPermissionApiMapper;
    @Resource
    private UpmsUserOnlineService upmsUserOnlineService;
    @Resource
    GlobalCacheService globalCacheService;

    @Override
    public BaseResult page(PageVo pageVo) {
        List<UpmsUser> users = pageVo.getRecords();
        List<JSONObject> records = new ArrayList<>();
        users.forEach(user -> {
            JSONObject json = JSON.parseObject(JSONObject.toJSONString(user));
            records.add(json);
        });
        for (JSONObject user : records) {
            user.put("upmsOrganizations", upmsPermissionApiMapper.selectOrganizationUserByUserId(user.getString("id")));
        }
        pageVo.setRecords(records);
        return BaseResult.ok(pageVo);
    }

    /**
     * 保存用户
     *
     * @param upmsUser
     * @param userOrganization
     * @param role
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult saveUser(UpmsUser upmsUser, UpmsUserOrganization userOrganization, String role) {
        ConfigJson configJson = globalCacheService.getSystemConfigJson(Arrays.asList(
                SystemConfigConstants.INIT_PASSWORD
        ));
        String initPassword = configJson.getString(SystemConfigConstants.INIT_PASSWORD);
        upmsUser.setPassword(initPassword);
        upmsUser.setId(SnowflakeIdUtil.generateStrId());
        upmsUser.setIsLocked(BaseConstants.NO);
        upmsUser.setUserPinyin(ChineseCharToEn.getPinYinAll(upmsUser.getRealName()));
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(upmsUser.getPassword() + upmsUser.getSalt()));

        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andUserNameEqualTo(upmsUser.getUserName());
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (!users.isEmpty()) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "用户名已存在,请重新输入");
        }
        super.insertSelective(upmsUser);


        if (!StringUtil.isNull(userOrganization)) {
            configCompany(userOrganization, upmsUser.getId());
        }

        if (!StringUtil.isNullOrEmpty(role)) {
            configRole(StringUtil.strToListString(role, ","), upmsUser.getId());
        }

        return BaseResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult updateUser(UpmsUser upmsUser, UpmsUserOrganization userOrganization, String role) {
        upmsUser.setGmtModified(System.currentTimeMillis());
        upmsUser.setPassword(null);
        upmsUser.setSalt(null);
        upmsUser.setUserPinyin(ChineseCharToEn.getAllFirstLetters(upmsUser.getRealName()));

        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andUserNameEqualTo(upmsUser.getUserName()).andIdNotEqualTo(upmsUser.getId());
        List<UpmsUser> upmsUsers = upmsUserMapper.selectByExample(upmsUserExample);
        if (!upmsUsers.isEmpty()) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "用户名已存在,请重新输入");
        }

        super.updateByPrimaryKeySelective(upmsUser);

        if (!StringUtil.isNull(userOrganization)) {
            configCompany(userOrganization, upmsUser.getId());
        }

        if (!StringUtil.isNullOrEmpty(role)) {
            configRole(StringUtil.strToListString(role, ","), upmsUser.getId());
        }

        return BaseResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult removeUser(List<String> userIds) {
        //删除用户
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIdIn(userIds);
        super.deleteByExample(upmsUserExample);

        //删除角色
        UpmsUserRoleExample upmsUserRoleExample = new UpmsUserRoleExample();
        upmsUserRoleExample.createCriteria().andUserIdIn(userIds);
        upmsUserRoleMapper.deleteByExample(upmsUserRoleExample);

        //删除组织
        UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
        upmsUserOrganizationExample.createCriteria().andUserIdIn(userIds);
        upmsUserOrganizationMapper.deleteByExample(upmsUserOrganizationExample);
        return BaseResult.ok();
    }


    @Override
    public BaseResult validateExistByField(String id, String field, String value) {
        boolean flag = true;
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        UpmsUserExample.Criteria criteria = upmsUserExample.createCriteria();
        if (!StringUtil.isNullOrEmpty(id)) {
            criteria.andIdNotEqualTo(id);
        }
        switch (field) {
            case "userName":
                criteria.andUserNameEqualTo(value);
                break;
            case "userCode":
                criteria.andUserCodeEqualTo(value);
                break;
            case "mobile":
                criteria.andMobileEqualTo(value);
                break;
            case "idNumber":
                criteria.andIdNumberEqualTo(value);
                break;
            default:
                flag = false;
        }
        if (flag) {
            return BaseResult.ok(upmsUserMapper.countByExample(upmsUserExample) > 0);
        } else {
            return BaseResult.error(BaseResultEnum.FAILED, "暂未配置对字段" + field + "的校验");
        }
    }

    @Override
    public BaseResult getUserById(String id) {
        UpmsUser upmsUser = upmsUserMapper.selectByPrimaryKey(id);
        UpmsUserVo userVo = new UpmsUserVo();
        BeanUtils.copyProperties(upmsUser, userVo);
        userVo.setUpmsOrganizations(upmsPermissionApiMapper.selectOrganizationUserByUserId(id));
        userVo.setUpmsRoles(upmsPermissionApiMapper.selectRoleByUserId(id));
        return BaseResult.ok(userVo);
    }

    @Override
    public BaseResult getUserByMobile(String mobile) {
        if (!mobile.matches(RegularExpressionConstants.MOBILE)) {
            return BaseResult.error("请输入正确的手机号码!");
        }
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andMobileEqualTo(mobile);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            return BaseResult.error("暂无此手机号用户信息!");
        }
        return BaseResult.ok(users.get(0));
    }

    @Override
    public BaseResult login(String sessionId, String username, String password, String loginIp, LoginTypeEnum loginTypeEnum) {
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO).andUserNameEqualTo(username);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            upmsUserLoginHistoryService.loginHistory(null, username, null, BaseResultEnum.USER_IS_EXIST_NO.getMessage(), BaseConstants.NO, loginIp, loginTypeEnum);
            return BaseResult.error(BaseResultEnum.USER_IS_EXIST_NO, null);
        }
        UpmsUser user = users.get(0);
        LOGGER.info("You input password is:" + password);
        if (!Md5Util.md5(password + user.getSalt()).equals(user.getPassword())) {
            upmsUserLoginHistoryService.loginHistory(null, username, null, BaseResultEnum.ERROR_PASSWORD.getMessage(), BaseConstants.NO, loginIp, loginTypeEnum);
            return BaseResult.error(BaseResultEnum.ERROR_PASSWORD, null);
        }
        return login(user, loginIp, sessionId, loginTypeEnum);
    }

    @Override
    public BaseResult mobileLogin(String sessionId, String mobile, String loginIp, LoginTypeEnum loginTypeEnum) {
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO).andMobileEqualTo(mobile);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            upmsUserLoginHistoryService.loginHistory(null, mobile, null, BaseResultEnum.USER_IS_EXIST_NO.getMessage(), BaseConstants.NO, loginIp, loginTypeEnum);
            return BaseResult.error(BaseResultEnum.USER_IS_EXIST_NO, null);
        }
        UpmsUser user = users.get(0);
        return login(user, loginIp, sessionId, loginTypeEnum);
    }

    @Override
    public BaseResult scanLogin(String sessionId, String username, String loginIp, LoginTypeEnum loginTypeEnum) {
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO).andUserNameEqualTo(username);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            upmsUserLoginHistoryService.loginHistory(null, username, null, BaseResultEnum.USER_IS_EXIST_NO.getMessage(), BaseConstants.NO, loginIp, loginTypeEnum);
            return BaseResult.error(BaseResultEnum.USER_IS_EXIST_NO, null);
        }
        UpmsUser user = users.get(0);

        return login(user, loginIp, sessionId, loginTypeEnum);
    }

    private BaseResult login(UpmsUser user, String loginIp, String sessionId, LoginTypeEnum loginTypeEnum) {
        try {
            if (BaseConstants.YES == user.getIsLocked()) {
                upmsUserLoginHistoryService.loginHistory(null, user.getUserName(), null, BaseResultEnum.ACCOUNT_LOCKED.getMessage(), BaseConstants.NO, loginIp, loginTypeEnum);
                return BaseResult.error(BaseResultEnum.ACCOUNT_LOCKED, null);
            }

            CacheUserVO userVO = new CacheUserVO(UserTypeEnum.ADMIN);
            /**
             * 用户基本信息
             */
            userVO.setMobile(user.getMobile());
            userVO.setEmail(user.getEmail());
            userVO.setUsername(user.getUserName());
            userVO.setId(user.getId());
            userVO.setRealName(user.getRealName());
            userVO.setStatus(user.getIsLocked());
            userVO.setAdmin(user.getIsAdmin() == 1);
            userVO.setAvatar(user.getAvatar());
            userVO.setInitPassword(user.getIsInitPassword() != 0);
            userVO.setUserCode(user.getUserCode());
            userVO.setSessionId(sessionId);


            //用户组织信息
            userVO = setLoginUserOrganization(userVO,null);

            /**
             * 用户菜单与权限
             */
            List<String> perms = new ArrayList<>();
            List<Object> menuPerms = new ArrayList<>();
            List<UpmsPermission> permissions = upmsPermissionApiMapper.selectPermissionByUserId(user.getId());
            for (UpmsPermission permission : permissions) {
                if (2 == permission.getType()) {
                    perms.add(permission.getPermissionValue());
                } else {
                    JSONObject json = new JSONObject();
                    json.put("title", permission.getName());
                    json.put("code", permission.getPermissionValue());
                    json.put("icon", permission.getIcon());
                    json.put("orders", permission.getOrders());
                    menuPerms.add(json);
                }
            }
            userVO.setPerms(perms);
            userVO.setMenuPerms(menuPerms);

            /**
             * 用户角色
             */
            List<UpmsRole> upmsRoles = upmsPermissionApiMapper.selectRoleByUserId(user.getId());
            List<CacheRoleVo> roleVos = new ArrayList<>();
            for (UpmsRole upmsRole : upmsRoles) {
                CacheRoleVo roleVo = new CacheRoleVo();
                roleVo.setRoleCode(upmsRole.getCode());
                roleVo.setRoleName(upmsRole.getName());
                roleVo.setDataScope(upmsRole.getDataScope());
                roleVos.add(roleVo);
            }
            userVO.setCacheRoleVos(roleVos);


            String accessToken = JwtUtil.createToken(userVO);
            System.out.println("----------------------------------"+userCacheService.cacheUser(accessToken, userVO));
            upmsUserLoginHistoryService.loginHistory(userVO.getId().toString(), user.getUserName(), userVO.getRealName(), "登录成功", BaseConstants.YES, loginIp, loginTypeEnum);
            upmsUserOnlineService.loginUserToUserOnline(accessToken, userVO, loginIp);
            return BaseResult.ok(accessToken);
        } catch (Exception e) {
            return ExceptionUtil.formatException(e);
        }

    }

    private CacheUserVO setLoginUserOrganization(CacheUserVO userVO, String orgId) {
        List<UpmsOrganization> organizations = upmsPermissionApiMapper.selectOrganizationByUserId(userVO.getId().toString());
        if (!organizations.isEmpty()) {
            List<UpmsOrganization> units = new ArrayList<>();
            List<UpmsOrganization> departments = new ArrayList<>();
            for (UpmsOrganization organization : organizations) {
                if (Byte.valueOf("1").equals(organization.getType())) {
                    units.add(organization);
                }
                if (Byte.valueOf("2").equals(organization.getType())) {
                    departments.add(organization);
                }
            }
            if (units.isEmpty()) {
                throw new BusinessException("当前登陆用户暂未分配组织!");
            }

            UpmsOrganization upmsOrganization = null;
            if (StringUtil.isNullOrEmpty(orgId)) {
                upmsOrganization = units.get(0);
            } else {
                for (UpmsOrganization organization : units) {
                    if (organization.getId().equals(orgId)) {
                        upmsOrganization = organization;
                        break;
                    }
                }
            }

            userVO.setCacheOrganizationVo(analyticalAssemblyOrganization(upmsOrganization));

            /**
             * 机构
             */
            List<CacheOrganizationVo> cacheOrganizationVos = new ArrayList<>();
            for (UpmsOrganization organization : units) {
                cacheOrganizationVos.add(analyticalAssemblyOrganization(organization));
            }
            userVO.setCacheOrganizationVos(cacheOrganizationVos);

            /**
             * 部门
             */
            List<CacheDepartmentVo> cacheDepartmentVos = new ArrayList<>();
            /**
             * 保留代码
             */
            /*if (!departments.isEmpty()) {
                userVO.setCacheDepartmentVo(analyticalAssemblyDepartment(departments.get(0)));
                for (UpmsOrganization organization : departments) {
                    cacheDepartmentVos.add(analyticalAssemblyDepartment(organization));
                }
            }*/
            /**
             * 1.获得当前组织编码
             * 2.组织编码首位标识，替换成部门标识
             * 3.匹配部门标识，查找属于组织的部门
             */
            String orgCode = upmsOrganization.getOrganizationCode();
            orgCode = orgCode.replace("1-", "2-");
            if (!departments.isEmpty()) {
                for (UpmsOrganization department : departments) {
                    if (department.getOrganizationCode().contains(orgCode)) {
                        cacheDepartmentVos.add(analyticalAssemblyDepartment(department));
                    }
                }
            }
            if (!cacheDepartmentVos.isEmpty()) {
                userVO.setCacheDepartmentVo(cacheDepartmentVos.get(0));
            }else{
                userVO.setCacheDepartmentVo(null);
            }
            userVO.setCacheDepartmentVos(cacheDepartmentVos);
        }
        return userVO;
    }

    private CacheOrganizationVo analyticalAssemblyOrganization(UpmsOrganization upmsOrganization) {
        Map<String, String> regions = Maps.newHashMapWithExpectedSize(7);
        String regionDetails = upmsOrganization.getRegionDetails();
        if (!StringUtil.isNullOrEmpty(regionDetails)) {
            regions.put("provinceId", regionDetails.split(";")[0].split(":")[0]);
            regions.put("cityId", regionDetails.split(";")[1].split(":")[0]);
            regions.put("areaId", regionDetails.split(";")[2].split(":")[0]);
            regions.put("streetId", regionDetails.split(";")[3].split(":")[0]);
            regions.put("province", regionDetails.split(";")[0].split(":")[1]);
            regions.put("city", regionDetails.split(";")[1].split(":")[1]);
            regions.put("area", regionDetails.split(";")[2].split(":")[1]);
            regions.put("street", regionDetails.split(";")[3].split(":")[1]);
        }
        CacheOrganizationVo organizationVo = new CacheOrganizationVo(
                upmsOrganization.getId(),
                upmsOrganization.getPid(),
                upmsOrganization.getOrganizationCode(),
                upmsOrganization.getOrganizationName(),
                upmsOrganization.getLogo(),
                upmsOrganization.getOrganizationLevel(),
                upmsOrganization.getOrganizationCategory(),
                String.valueOf(upmsOrganization.getType()),
                upmsOrganization.getChargeInfo(),
                JSON.toJSONString(regions)
        );
        return organizationVo;
    }

    private CacheDepartmentVo analyticalAssemblyDepartment(UpmsOrganization upmsOrganization) {

        CacheDepartmentVo cacheDepartmentVo = new CacheDepartmentVo(
                upmsOrganization.getId(),
                upmsOrganization.getOrganizationCode(),
                upmsOrganization.getOrganizationName()
        );
        return cacheDepartmentVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult register(String mobile, String realName, String password, String passwordAgain) {
        ConfigJson configJson = globalCacheService.getSystemConfigJson(Arrays.asList(
                SystemConfigConstants.DEFAULT_ROLE
        ));
        String defaultRole = configJson.getString(SystemConfigConstants.DEFAULT_ROLE);
        if (!password.equals(passwordAgain)) {
            return BaseResult.error("确认密码输入错误！");
        }
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andMobileEqualTo(mobile);
        if (upmsUserMapper.countByExample(upmsUserExample) > 0) {
            return BaseResult.error("输入的手机号不存在,请重新输入！");
        }
        UpmsRoleExample upmsRoleExample = new UpmsRoleExample();
        upmsRoleExample.createCriteria().andCodeEqualTo(defaultRole);
        List<UpmsRole> roles = upmsRoleMapper.selectByExample(upmsRoleExample);
        if (roles.isEmpty()) {
            return BaseResult.error("系统缺少【" + defaultRole + "】角色，暂无法注册用户！");
        }

        UpmsUser upmsUser = new UpmsUser();
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(password + upmsUser.getSalt()));
        upmsUser.setMobile(mobile);
        upmsUser.setUserName(mobile);
        upmsUser.setRealName(realName);
        upmsUser.setIsInitPassword(Byte.valueOf("0"));
        upmsUser.setCategory("1:默认分类");
        upmsUser.setUserCode(SnowflakeIdUtil.generateStrId());
        upmsUser.setUserPinyin(ChineseCharToEn.getAllFirstLetters(realName));
        super.insertSelective(upmsUser);

        configRole(StringUtil.strToListString(roles.get(0).getId(), ","), upmsUser.getId());
        return BaseResult.ok();
    }

    @Override
    public BaseResult joinOrg(CacheUserVO cacheUserVO, String invitationCode, String realName) {
        if (!cacheUserVO.getRealName().equals(realName)) {
            return BaseResult.error("真实姓名与登录账号信息不符，请重新输入！");
        }
        String userId = StringUtil.getString(cacheUserVO.getId());
        Long organizationId;
        try {
            organizationId = ShareCodeUtil.codeToId(invitationCode);
        } catch (Exception e) {
            return BaseResult.error("无效的邀请码！");
        }
        UpmsOrganization organization = upmsOrganizationMapper.selectByPrimaryKey(StringUtil.getString(organizationId));
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("无效的邀请码！");
        }
        UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
        upmsUserOrganizationExample.createCriteria()
                .andUserIdEqualTo(userId)
                .andOrganizationIdEqualTo(StringUtil.getString(organizationId));
        if (upmsUserOrganizationMapper.countByExample(upmsUserOrganizationExample) > 0) {
            return BaseResult.error("您已经加入该组织，无需再次加入！");
        }
        UpmsUserOrganization upmsUserOrganization = new UpmsUserOrganization();
        upmsUserOrganization.setId(SnowflakeIdUtil.generateStrId());
        upmsUserOrganization.setIsDeleted(BaseConstants.NO);
        upmsUserOrganization.setGmtCreated(System.currentTimeMillis());
        upmsUserOrganization.setGmtModified(System.currentTimeMillis());
        upmsUserOrganization.setOrganizationId(StringUtil.getString(organizationId));
        upmsUserOrganization.setUserId(userId);
        upmsUserOrganization.setType(Byte.valueOf("1"));
        upmsUserOrganization.setFullOrganizationId(StringUtil.getString(organizationId));
        upmsUserOrganizationMapper.insertSelective(upmsUserOrganization);
        cacheUserVO = setLoginUserOrganization(cacheUserVO,upmsUserOrganization.getId());
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult leaveOrg(CacheUserVO cacheUserVO, String organizationId) {
        UpmsOrganization organization = upmsOrganizationMapper.selectByPrimaryKey(organizationId);
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("企业不存在！");
        }
        UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
        upmsUserOrganizationExample.createCriteria()
                .andOrganizationIdEqualTo(organizationId)
                .andUserIdEqualTo(StringUtil.getString(cacheUserVO.getId()));
        upmsUserOrganizationMapper.deleteByExample(upmsUserOrganizationExample);
        cacheUserVO = setLoginUserOrganization(cacheUserVO,null);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult enterOrg(CacheUserVO cacheUserVO, String organizationId) {
        UpmsOrganization organization = upmsOrganizationMapper.selectByPrimaryKey(organizationId);
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("企业不存在！");
        }
        //cacheUserVO.setCacheOrganizationVo(analyticalAssemblyOrganization(organization));
        cacheUserVO = setLoginUserOrganization(cacheUserVO,organizationId);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);

    }

    @Override
    public BaseResult changeDept(CacheUserVO cacheUserVO, String deptId) {
        UpmsOrganization organization = upmsOrganizationMapper.selectByPrimaryKey(deptId);
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("部门不存在！");
        }
        cacheUserVO.setCacheDepartmentVo(analyticalAssemblyDepartment(organization));
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult checkJoinOrg(String userId, String invitationCode) {
        Long organizationId = -1L;
        try {
            organizationId = ShareCodeUtil.codeToId(invitationCode);
        } catch (Exception e) {
            return BaseResult.error("无效的邀请码！");
        }
        UpmsOrganization organization = upmsOrganizationMapper.selectByPrimaryKey(StringUtil.getString(organizationId));
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("无效的邀请码！");
        }
        UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
        upmsUserOrganizationExample.createCriteria()
                .andUserIdEqualTo(userId)
                .andOrganizationIdEqualTo(StringUtil.getString(organizationId));
        if (upmsUserOrganizationMapper.countByExample(upmsUserOrganizationExample) > 0) {
            return BaseResult.error("您已经加入该组织，无需再次加入！");
        }
        return BaseResult.ok();
    }

    @Override
    public BaseResult modifyPassword(String userId, String oldPassword, String newPassword, String newPasswordAgain) {
        UpmsUser upmsUser = upmsUserMapper.selectByPrimaryKey(userId);
        if (oldPassword.equals(newPassword)) {
            return BaseResult.error(BaseResultEnum.ERROR_PASSWORD, "新旧密码不能一致");
        }
        if (!Md5Util.md5(oldPassword + upmsUser.getSalt()).equals(upmsUser.getPassword())) {
            return BaseResult.error(BaseResultEnum.ERROR_PASSWORD, "旧密码输入错误");
        }
        if (!newPassword.equals(newPasswordAgain)) {
            return BaseResult.error("确认密码输入错误！");
        }
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(newPassword + upmsUser.getSalt()));
        upmsUser.setGmtModified(System.currentTimeMillis());
        upmsUser.setIsInitPassword(BaseConstants.NO);
        return super.updateByPrimaryKeySelective(upmsUser);
    }

    @Override
    public BaseResult forgotPassword(String mobile, String password, String passwordAgain) {
        if (!password.equals(passwordAgain)) {
            return BaseResult.error("确认密码输入错误！");
        }
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andMobileEqualTo(mobile);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            return BaseResult.error("输入的手机号不存在,请重新输入！");
        }
        UpmsUser upmsUser = users.get(0);
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(password + upmsUser.getSalt()));
        upmsUser.setGmtModified(System.currentTimeMillis());
        return super.updateByPrimaryKeySelective(upmsUser);
    }

    @Override
    public BaseResult modifyAvatar(String avatar, CacheUserVO cacheUserVO) {
        UpmsUser user = upmsUserMapper.selectByPrimaryKey(cacheUserVO.getId());
        if (StringUtil.isNull(user)) {
            return BaseResult.error("查无此用户！");
        }
        user.setAvatar(avatar);
        super.updateByPrimaryKeySelective(user);
        cacheUserVO.setAvatar(avatar);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult modifyUserName(String userName, String id) {
        UpmsUser user = upmsUserMapper.selectByPrimaryKey(id);
        if (StringUtil.isNull(user)) {
            return BaseResult.error("查无此用户！");
        }
        if (StringUtil.isNullOrEmpty(user.getUserName())) {
            user.setUserName(userName);
        } else {
            if (userName.equals(user.getUserName())) {
                return BaseResult.error("不能与原用户名一致,请重新输入！");
            } else {
                user.setUserName(userName);
            }
        }
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andUserNameEqualTo(userName).andIdNotEqualTo(id);
        if (upmsUserMapper.countByExample(upmsUserExample) > 0) {
            return BaseResult.error("用户名已存在,请重新输入！");
        }
        super.updateByPrimaryKeySelective(user);
        return BaseResult.ok();
    }

    @Override
    public BaseResult modifyEmail(String newEmail, CacheUserVO cacheUserVO) {
        if (!StringUtil.isNullOrEmpty(cacheUserVO.getEmail())) {
            if (newEmail.equals(cacheUserVO.getEmail())) {
                return BaseResult.error("新旧邮箱不能一致！");
            }
            UpmsUserExample upmsUserExample = new UpmsUserExample();
            upmsUserExample.createCriteria().andEmailEqualTo(newEmail).andIdNotEqualTo(StringUtil.getString(cacheUserVO.getId()));
            if (upmsUserMapper.countByExample(upmsUserExample) > 0) {
                return BaseResult.error("新邮箱号已被使用,请重新输入!");
            }
        }

        UpmsUser user = upmsUserMapper.selectByPrimaryKey(cacheUserVO.getId());
        if (StringUtil.isNull(user)) {
            return BaseResult.error("查无此用户！");
        }

        user.setEmail(newEmail);
        super.updateByPrimaryKeySelective(user);
        cacheUserVO.setEmail(newEmail);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult modifyMobile(String newMobile, CacheUserVO cacheUserVO) {
        if (!StringUtil.isNullOrEmpty(cacheUserVO.getMobile())) {
            if (newMobile.equals(cacheUserVO.getMobile())) {
                return BaseResult.error("新旧手机号不能一致！");
            }
            UpmsUserExample upmsUserExample = new UpmsUserExample();
            upmsUserExample.createCriteria().andMobileEqualTo(newMobile).andIdNotEqualTo(StringUtil.getString(cacheUserVO.getId()));
            if (upmsUserMapper.countByExample(upmsUserExample) > 0) {
                return BaseResult.error("新手机号已被使用,请重新输入!");
            }
        }

        UpmsUser user = upmsUserMapper.selectByPrimaryKey(cacheUserVO.getId());
        if (StringUtil.isNull(user)) {
            return BaseResult.error("查无此用户！");
        }
        user.setMobile(newMobile);
        super.updateByPrimaryKeySelective(user);
        cacheUserVO.setMobile(newMobile);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult unlock(String userId, String password, String ip) {
        UpmsUser upmsUser = upmsUserMapper.selectByPrimaryKey(userId);
        if (!Md5Util.md5(password + upmsUser.getSalt()).equals(upmsUser.getPassword())) {
            return BaseResult.error(BaseResultEnum.ERROR_PASSWORD, "密码输入错误");
        }
        return BaseResult.ok();
    }

    @Override
    public BaseResult initialPassword(List<String> ids) {
        ConfigJson configJson = globalCacheService.getSystemConfigJson(Arrays.asList(
                SystemConfigConstants.INIT_PASSWORD
        ));
        String initPassword = configJson.getString(SystemConfigConstants.INIT_PASSWORD);
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIdIn(ids);
        UpmsUser upmsUser = new UpmsUser();
        upmsUser.setPassword(initPassword);
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(upmsUser.getPassword() + upmsUser.getSalt()));
        upmsUser.setIsInitPassword(BaseConstants.YES);
        int i = upmsUserMapper.updateByExampleSelective(upmsUser, upmsUserExample);
        if (i == 0) {
            return BaseResult.error(BaseResultEnum.FAILED, "初始化密码失败");
        } else {
            return BaseResult.ok("初始化密码成功,密码为'" + initPassword + "'");
        }
    }

    @Override
    public BaseResult changeIsLocked(String id, Boolean isLocked) {
        UpmsUser upmsUser = upmsUserMapper.selectByPrimaryKey(id);
        upmsUser.setIsLocked(Boolean.TRUE.equals(isLocked) ? BaseConstants.YES : BaseConstants.NO);
        upmsUserMapper.updateByPrimaryKeySelective(upmsUser);
        return BaseResult.ok();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult adjustmentOrg(String id, String targetOrg) {
        UpmsUser user = upmsUserMapper.selectByPrimaryKey(id);
        if (StringUtil.isNull(user)) {
            return BaseResult.error("用户不存在");
        }
        //  configCompany(StringUtil.strToListString(targetOrg, ","), id);
        return BaseResult.ok();
    }

    private void configRole(List<String> roleIds, String userId) {
        List<UpmsRole> upmsRoles = upmsPermissionApiMapper.selectRoleByUserId(userId);
        List<String> listUserRoleId = new ArrayList<>();
        for (UpmsRole upmsRole : upmsRoles) {
            listUserRoleId.add(upmsRole.getId());
        }
        UpmsUserRoleExample upmsUserRoleExample = new UpmsUserRoleExample();
        UpmsUserRoleExample.Criteria criteriaUserRole = upmsUserRoleExample.createCriteria().andUserIdEqualTo(userId);
        if (!StringUtil.isNull(roleIds)) {
            /**
             * 新增
             */
            List<String> notExists = new ArrayList<>(roleIds);
            notExists.removeAll(listUserRoleId);
            if (!notExists.isEmpty()) {
                List<UpmsUserRole> listUserRole = new ArrayList<>();
                for (String userRoleId : notExists) {
                    UpmsUserRole upmsUserRole = new UpmsUserRole();
                    upmsUserRole.setId(SnowflakeIdUtil.generateStrId());
                    upmsUserRole.setIsDeleted(BaseConstants.NO);
                    upmsUserRole.setGmtCreated(System.currentTimeMillis());
                    upmsUserRole.setGmtModified(System.currentTimeMillis());
                    upmsUserRole.setRoleId(userRoleId);
                    upmsUserRole.setUserId(userId);
                    listUserRole.add(upmsUserRole);
                }
                upmsUserRoleMapper.insertSelectiveBatch(listUserRole);
            }

            /**
             * 删除
             */
            List<String> currentNotExists = new ArrayList<>(listUserRoleId);
            currentNotExists.removeAll(roleIds);
            if (!currentNotExists.isEmpty()) {
                List<String> removeUserRole = new ArrayList<>();
                for (String userRoleId : currentNotExists) {
                    removeUserRole.add(userRoleId);
                }
                criteriaUserRole.andRoleIdIn(removeUserRole);
                upmsUserRoleMapper.deleteByExample(upmsUserRoleExample);
            }
        }

    }

    /**
     * 配置单位
     *
     * @param userOrganization
     * @param userId
     */
    private void configCompany(UpmsUserOrganization userOrganization, String userId) {

        if (Byte.valueOf("2").equals(userOrganization.getType())) {
            UpmsUserOrganization organization = new UpmsUserOrganization();
            String orgId = userOrganization.getFullOrganizationId().split(",")[0];
            organization.setOrganizationId(orgId);
            organization.setFullOrganizationId(orgId);
            organization.setType(Byte.valueOf("1"));
            organization.setOrders(1);
            configCompany(organization, userId);
        }
        UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
        upmsUserOrganizationExample.createCriteria()
                .andUserIdEqualTo(userId)
                .andOrganizationIdEqualTo(userOrganization.getOrganizationId());
        List<UpmsUserOrganization> upmsUserOrganizations = upmsUserOrganizationMapper.selectByExample(upmsUserOrganizationExample);
        if (upmsUserOrganizations.isEmpty()) {
            UpmsUserOrganization upmsUserOrganization = new UpmsUserOrganization();
            upmsUserOrganization.setId(SnowflakeIdUtil.generateStrId());
            upmsUserOrganization.setIsDeleted(BaseConstants.NO);
            upmsUserOrganization.setGmtCreated(System.currentTimeMillis());
            upmsUserOrganization.setGmtModified(System.currentTimeMillis());
            upmsUserOrganization.setOrganizationId(userOrganization.getOrganizationId());
            upmsUserOrganization.setUserId(userId);
            upmsUserOrganization.setJob(userOrganization.getJob());
            upmsUserOrganization.setPhone(userOrganization.getPhone());
            upmsUserOrganization.setOrders(userOrganization.getOrders());
            upmsUserOrganization.setType(userOrganization.getType());
            upmsUserOrganization.setFullOrganizationId(userOrganization.getFullOrganizationId());
            upmsUserOrganizationMapper.insertSelective(upmsUserOrganization);
        } else {
            UpmsUserOrganization organization = upmsUserOrganizations.get(0);
            organization.setJob(userOrganization.getJob());
            organization.setPhone(userOrganization.getPhone());
            organization.setOrders(userOrganization.getOrders());
            organization.setType(userOrganization.getType());
            organization.setFullOrganizationId(userOrganization.getFullOrganizationId());
            upmsUserOrganizationMapper.updateByPrimaryKeySelective(organization);
        }
    }

}
